home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Merciful 4
/
Merciful - Disc 4.iso
/
software
/
p
/
psychotoads.dms
/
psychotoads.adf
/
a4
< prev
next >
Wrap
Text File
|
1989-03-31
|
31KB
|
927 lines
4: BASIC PRINCIPLES 35
-----------------------------
This chapter discusses the ground rules used to construct AMOS Basic
programs and shows you how to improve your programming style with the
help of AMOS Basic procedures.
Variables
=========
Variables are the names used to refer to storage locations inside a
computer. These locations hold the results of the calculations
performed in one of your programs.
The choise of variable names is entirely up to you, and can include
any string of letters or numbers. There are only a couple of
restrictions. All variable names MUST begin with a letter and cannot
commence with an existing AMOS Basic instruction. However it is
perfectly permissible to use these keywords inside a name. So variables
such as VPRINT or SCORE are fine.
Variable names must be continuous, and may not contain embedded
spaces. If a space is required, it's a possible to substitute a "_"
character instead.
Here are some examples of illegal names. The illegal bits are
underlined to make things clearer.
WHILE$, 5C, MODERN#, TOAD
----- - --- --
Types of variables
==================
AMOS Basic allows you to use three different types of variables in your
programs.
Integers
--------
Unlike most other Basics, AMOS initially assumes that all variables are
integers. Integers are whole numbers such as 1,3 or 8, and are ideal
for holding the values used in your games.
Since integer arithmetic is much faster than the normal floating
point operations, using integers in you programs can lead to dramatic
improvements in speed. Each integer is stored in four bytes and can
range from -147'483'648 to +147'483'648. Examples of integer variables:
A, NUMBER, SCORE, LIVES
Real numbers 36
------------
In AMOS Basic these variables are always followed by a hash (#)
character. Real numbers can hold fractional values such as 3.1 or 1.5.
They correspond directly to the standard variables used in most other
versions of Basic. Each real variable is stored in four bytes and can
range between 1E-14 and 1E-15. All values are accurate to a precision
of seven decimal digits. Examples:
P#, NUMBER#, TEST#
String variables
----------------
String variables contain text rather than numbers. They are
distinguished from normal variables by the $ character at the end. The
length of your text can be anything from 0 to 65'500 characters.
Examples of string variables:
NAME$, PATH$, ALIEN$
Giving a variable a value
=========================
Assigning a value to a variable is easy. Simply choose an appropriate
name and assign it to value using the "=" statement.
VAR=10
This loads the variable VAR with a value of 10.
A$="Hello"
This assigns string "Hello" to a variable A$.
Arrays
======
Any list of variables can be combined together in the form of an array.
Arrays are created using the DIM instruction.
DIM (dimension an array)
DIM var(x,y,z,...)
DIM defines a table of variables in your AMOS Basic program. These
tables may have as manu dimensions as you want, but each dimension is
limited to a maximum of 65'000 elements. Example:
Dim A$(10),B(10,10),C#(10,10,10)
In order to access an element in the array you simply type the array
name followed by the index numbers. These numbers are separated by
commas and are enclosed between round brackets (). Note that the
element numbers of these arrays always start from zero. Example:
Dim ARRAY(10)
ARRAY(0)=10:ARRAY(1)=15
Print ARRAY(1);ARRAY(0)
( result: 15 10 )
Constants 37
=========
Constants are simply numbers or strings which are assigned to a
variable or used in one of your calculations. They are called constants
because they don't charge during the course of your program. The
following values are all constants:
1, 42, 3.141, "Hello"
As a default, all numeric constants are treated as integers. Any
floating point assignments to an integer variable are automatically
converted to a whole number before use. Examples:
A=3.141:Print A
( result: 3)
Print 19/2
( result: 9)
Constants can also be input using binary or hexadecimal notation.
Binary numbers are signified by preceding them with a % character, and
hexadecimal numbers are denoted by a $ sign. Here's number 255:
Decimal: 255
Hexadecimal: $FF
Binary: $11111111
Note that any numbers you type in AMOS Basic are automatically
converted to special internal format. When you list your program these
numbers are expanded back into their original form. Since AMOS Basic
prints all numbers in a standard way, this will often lead to minor
discrepancies between the number you entered and the number which is
displayed in your listing. However the value of the number will remain
exactly the same. Floating point constants are distinguished from
integers by a decimal point. If this point is not used, the number will
always be assumed to be an integer, even if this number occurs inside a
floating point expression. Take the following example:
For X=1 To 10000
A#=A#+2
Next X
Every time the expression in this program is evaluated, the "2" will be
laboriously converted into a real number. So this routine will be
inherently slower than the equivalent program below:
For X=1 To 10000
A#=A#+2.0
Next X
This program executes over 25% faster than the original one because the
constant is now stored directly in floating point format. You should
always remember to place a decimal oint after a floating point constant
even if it is a whole number. Incidentally, if you mix floating point
numbers and integers, the result will always be returned as a real
number. Example:
Print 19.0/2
( result: 9.5 )
Print 3.141+10
( result: 13.141 )
Arithmetic operations 38
=====================
The following arithmetic operations can be used in a numeric
expression:
^ power
/ * divide and multiply
MOD modulo operator (remainder of a division)
+ - plus and minus
AND logical AND
OR logical OR
NOT logical NOT
We've listed these operations in descending order of their priority.
This priority refers to the sequence in which the various sections of
an arithmetic expressions are evaluated. Operations with the highest
priority are always calculated first.
INC (add 1 to an integer variable) 39
INC var
INC adds 1 to an integer variable using a single 68000 instruction. It
is logically equivalent to the expression var=var+1, but faster.
Example:
A=10:Inc A:Print A
( result: 11 )
DEC (subtract 1 from an integer variable)
DEC var
This instruction subtracts 1 from the integer variable var. Example:
A=2:Dec A:Print A
( result: 1 )
ADD (fast integer addition)
ADD v,exp [,base TO top]
The standard from of this instruction immediately adds the result of
the expression exp to the integer variable v. It's equivalent to the
line: V=V+EXP
The only significant difference between the two statements is that
ADD performs around 40% faster. Note that the variable v must be an
integer. Example:
Timer=0
For X=1 To 1000
Add T,X
Next X
Print T,Timer
( result: 500500 7 )
The second version of ADD is a little more complicated. It is
effectively identical to the following code (but faster):
V=V+A
If V<Base Then V=Top
If V>Base Then V=Base
Example:
Dim A(10)
For X=0 To 10:A(X)=X:Next X
V=0
Repeat
Add V,1,1 To 10
Print A(V)
Until V=100:rem This is an infinite loop as V is always less
than 10!
As you can see, ADD is ideal for handing circular or repetitive loops
in your games.
String operations 40
=================
Like most versions of Basic, AMOS will happily allow you to add two
strings together.
A$="AMOS"+" Basic"
Print A$
( result: AMOS Basic )
But AMOS also lets you perform subtraction as well. This operation
works by removing all occurrences of the second string from the first.
Print "AMOS BASIC"-"AMO"
( result: S BASIC )
Comparisons between two strings are performed on a character by
character basis using the Ascii values of the appropriate letters:
"AA"<"BB"
"Filename"="Filename"
"X&">"X#"
"HELLO"<"hello"
Parameters 41
==========
The values you enter into an AMOS Basic instruction are known as
parameters. i.e
Inc N
Add A,10
Ink 1,2,3
The parameters in the above instructions are N,A,10,1,2 and 3
respectively. Occasionally, some of the parameters of a command can be
ommitted from an instruction. In this case, any unused values will
automatically be assigned a number by default. Example:
Ink 5,,
This changes the ink colour without affecting either the paper or
outline colours.
Line numbers and labels
=======================
Labels
======
Labels are just a convenient way of marking a point in your AMOS Basic
programs. They consist of a string of characters formed using the same
rules as AMOS variables. Labels should always be placed at the start of
the line, and must be followed immediately by a ":" character. There
should be no spaces between the label and the colon. Example:
TESTLABEL:
Print "Hi There!"
Goto TESTLABEL
This program can be aborted by pressing CTRL+C...
Procedures 42
==========
Procedures allow you to concentrate your efforts on just one problem at
a time without the distractions provided by the rest of your program.
Once you've written your procedures you can then quickly combine them
in your finished program. AMOS procedures are totally independent
program modules which can have their own program lines, variables, and
even data statements.
PROCEDURE (create an AMOS Basic procedure)
Procedure NAME[parameter list]
: :
End Proc[Expression]
This defines an AMOS Basic procedure called NAME. NAME is a string of
characters which identify the procedure. It is constructed in exactly
the same way as a normal Basic variable. Note that it's perfectly
acceptable t ouse identical names for procedures, variables and labels.
AMOS will automatically work out which object you are referring to from
the context of the line.
Procedures are similar to the GOSUB commands found in earlier
versions of Basic. Here's an example of a simple AMOS procedure:
Procedure ANSWER
Print "Forty-Two!"
End Proc
See how the procedure has been terminated with an END PROC statement.
You should also note that the Procedure and the End Proc directives are
both placed on their own separate lines. This is compulsory.
If you type the previous procedure into AMOS Basic as it stands, and
attempt to run it, nothing will happen. That's because you haven't
actually called the new procedure from your Basic Program. This can be
achieved by simply entering its name at the appropriate point in the
program. As an example, enter the following line at the start of the
program and run it to see the result of the procedure.
ANSWER
IMPORTANT! When you are using several procedures on the same line, it's
advisable to add an extra space at the end of each statement. This will
avoid the risk of the procedure being confused with a label. For
example:
TEST : TEST : TEST Performs the test three times.
TEST:TEST:TEST Defines Label TEST and executes test 2x
Alternatively, you can preclude your Procedure calls with a Proc
statement like so:
Proc ANSWER
Example:
Proc ANSWER
Procedure ANSWER
Print "Forty-Two"
End Proc
If you run this program again, the procedure will be entered, and the
answer will be printed out on the screen. Although the procedure
definition is positioned at the end of the program, it's possible to
place it absolutely anywhere. Whenever AMOS encouters a Procedure
statement, it installs the procedure and immediately jumps to the final
End Proc. This means there is no danger of accidentally executing your
procedure by mistake. Once you've created a procedure, and tested it to
your satisfaction, you can suppress it in your listings using the fold
option from the main menu.
These folding procedures reduce the apparent complexity of your
listings and allow you to debug large programs without the distractions
of unimportant details. You can restore your procedure listings to the
screen at any time by selecting the 'unfold menu option'.
Local and global variables 43
--------------------------
All the variables you define inside your procedures are independent of
any other variables used in your program. These variables are said to
be "local" to your particular procedure. Here's an example which
illustrates this:
A=1000:B=42
TEST
Print A,B
Procedure TEST
Print A,B
End Proc
It should be apparent that the names A and B refer to completely
different variable depending on whether they are used inside or outside
the procedure TEST. The variables which occur outside a procedure are
"global" and cannot be accessed from within it. Let's take another
example:
Dim A(100)
For V=1 To 100: A(V)=V:Next V
TEST_FLAG=1
APRINT
End
Procedure APRINT
If TEST_FLAG=1
For P=1 To 100
Print A(P)
Next P
Endif
End Proc
This program may look pretty harmess but it contains two fatal errors.
Firstly, the value of TEST_FLAG inside the procedure will always have
a value of zero. So the loop between the IF and the ENDIF will never be
performed. That's because the version of TEST_FLAG within the procedure
is completely separate from the copy defined in the main program. Like
all variables, it's automatically assigned to zero the fist time it's
used.
Furthermore, the program won't even run! Since the global array a()
has been defined outside ARPINT, AMOS Basic will immediately report an
"array not dimensioned" error at the line:
Print A(P)
This type of error is extremely easy tomake. So it's vital that you
treat procedures as separate programs with their own independent set of
variables and instrcutions.
There are a couple of extensions to this system which make it easy
for you to transfer information between a procedure and your main
program. Once you're familiar with these commands you'll have few
problems in using procedures successfully in your programs.
Parameters and procedures 44
-------------------------
One possibility is to include a list of "parameter definitions" in your
procedure. This creates a group of local variables which can be loaded
directly from the main program. Here's an example:
Procedure HELLO[NAME$]
Print "Hello ";NAME$
End Proc
The value to be loaded into NAME$ is entered between square brackets as
part of the procedure call. So the HELLO procedure could be performed
in the following ways:
Rem Loads N$ into NAME$ and enters procedure
Input "What's your name";n$
HELLO[N$]
HELLO["Stephen"]
As you can see, the parameter system is general purpose and works
equally well with either variables or constants. Only the type of the
variables are significant.
This process can be used to transfer integer, real or string
variables. However you cannot pass entire arrays with this function. If
you want to enter several parameters you should separate your variables
using commas. For example:
Procedure POWER[A,B]
Procudure MERGE[A$,B$,C$]
These procedures might by called using lines like:
POWER[10,3]
MERGE["One","Two","Three"]
Shared variables 45
----------------
Another way of passing data between a procedure and the main program is
to use the SHARED instruction.
SHARED (defina a list of global variables)
SHARED variable list
SHARED is placed inside a procedure definition and takes a list of AMOS
Basic variables separated by commas. These variables are now treated as
global variables., and can be accessed directly from the main program.
Any arrays which you declare in this way should of course have been
previously dimensioned in your main program. Example:
A=1000:B=42
TEST
Print A,B
Procudure Test
Shared A,B
A=A+B:B=B+10
End Proc
TEST can now read and write information to the global variables A and
B. If you want to share an array you should define it like so:
Shared A(),B#(),C$() : Rem Share arrays A,B# and C$
GLOBAL (declare a list of global variables
from the main program)
GLOBAL variable list
When you're writing a large program, it's commonplace for a number of
procedures to share the same set of global variables. This provides a
simple method of transferring large amounts of information between your
various procedures. In order to simplify this process, we've included a
single command which can be used directly in your main program. GLOBAL
defines a list variables which can be accessed anywhere inside your
Basic program, without the need for an explicit SHARED statement in
your procedure.
Returning values from a procedure 46
---------------------------------
If a procedure needs to return a value which is only local to itself,
it must use the following command so that it can inform the calling
PROCEDURE command where to find the local variable
PARAM (return a parameter from a procedure)
PARAM
The PARAM functions provide you with a simple way of returning a result
from a procedure. They take the result of an optional expression in the
END PROC statement, and return it in one of the variables PARAM,
PARAM#, or PARAM$ depending on its type. Example:
MERGE_STRINGS["Amos"," ","Basic"]
Print PARAM$
Procedure MERGE_STRINGS[A$,B$,C$]
Print A$,B$,C$
End Proc
Note that END PROC may only return a single parameter in this way. The
PARAM functions will always contain the result of the most recently
executed procedure. Here's another example, this time showing the use
of the PARAM# function.
CUBE[3,0]
Print Param#
Procedure CUBE[A#]
C#=CUBE#*CUBE#*CUBE#
EndProc[C#]
Leaving a procedure 47
-------------------
POP PROC (leave a procedure immediately)
POP PROC
Normally, procedures will only return to the main program when the END
PROC instruction is reached. Sometimes, however, you need to exit a
procedure in a hurry. IN this case you can use the POP PROC function to
exit immediately.
Local DATA statements
---------------------
Any data statements defined inside one of your procedures are held
completely separately from those in the main program. This means each
procedure can have its own individual data areas.
Hints and tips
--------------
Here are a few guidelines which will help you make the most out of your
AMOS Basic procedures:
* It's perfectly legal for a proceduces to call itself, but this
recursion is limited by the amount of space used to store the local
variables. If your program runs out of memory you'll get an
appropriate error.
* All local variables are automatically discarded after the procedure
has finished executing.
Memory banks 48
============
AMOS Basic includes a number of powerful facilities for manipulating
sprites, bobs and music. The data required by these functions needs to
be stored along with the Basic program. AMOS Basic uses a special set
of 15 sections of memory for this purpose called "banks".
Each bank is referred to by a unique number ranging from 1 to 15.
Many of these banks can be used for all types of data, but some are
dedicated solely to one sort of information such as sprite definitions.
All sprite images are stored in bank 1. They can be loaded into memory
using a line like:
Load "AMOS_DATA:Sprites/Octopus.abk"
There are two different forms of memory bank: Permanent and temprorary.
Permanent banks only need to be defined once, and are subsequently
saved along with your program automatically. Temporary banks are much
more volatile and are reinitialized every time a program is run.
Furthermore, unlike permanent banks, temporary banks can be erased from
memory using the CLEAR command.
Types of memory bank
--------------------
AMOS Basic supports the following types of memory bank:
Class Stores Restrictions Type
----- ------ ------------ ----
Sprites Sprite or bob definitions Only bank 1 Permanent
Icons Holds icon definitions Only bank 2 Permanent
Music Contains sound track data Only bank 3 Permanent
Amal Used for AMAL data Only bank 4 Permanent
Samples The Sample Data banks 1-15 Permanent
Menu Stores MENU definition banks 1-15 Permanent
Chip work Temporary workspace banks 1-15 Temporary
Chip data Permanent workspace banks 1-15 Permanent
Fast work Temporary workspace banks 1-15 Temporary
Fast data Permanent workspace banks 1-15 Permanent
RESERVE (reserve a bank) 49
RESERVE AS type,bank,length
The banks used by your sprites or bobs are allocated automatically by
AMOS. The RESERVE command allows you to create any other banks which
you might require. Each different type of bank has its own unique
version of the RESERVE instruction.
RESERVE AS WORK bankno,length
Reserves "length" bytes for use as a temporary workspace. Whenever
possible this memory area will be allocated using fast memory, so you
shoudn't call this command in conjunction with instructions which need
to access to Amiga's blitter chip.
RESERCE AS CHIP WORK bankno,length
Allocates a workspace of size "length" using chip ram. You can check
whether there's enough chip ram available with the CHIP FREE function.
RESERCE AS CHIP DATA bankno,length
Reserves "length" bytes of memory from chip ram. This bank will be
automatically saved along with your AMOS programs.
Bank may be any number between 1 and 15. Since banks 1 to 5 are
normally reserved by the system, it's wisest to leave them alone. Note
that the only limit to the length of a bank is the amount of available
memory.
LISTBANK (list the banks in use)
LISTBANK lists the numbers of the banks currently reserved by a
program, along with their location and size. The listing is produced in
the following format:
Number Type Start Length
Normally the length of a bank is returned in bytes, but in case of
sprites and icons the value represents the total number of images in
the bank instead. The reason for this is that the storage of each image
can be anywhere in the Amiga's memory, the bank is therefore not a
continuous block of memory. So don't BSAVE a sprite bank, simply use
SAVE "filename.abk"
Deleting banks 50
--------------
During the course of a program you may need to clear some banks from
the memory so as to load in additional data. Sprites may need to change
for a new part of a game or a special piece of music is required to be
played. The ERASE command gives you quick control for data deletion.
ERASE (delete a bank)
ERASE b
ERASE deletes the contents of a memory bank. The bank number b can
range from 1 to 15. Note that any memory used by this bank is
subsequently freed for use by your program.
Bank parameter functions
------------------------
If you want to have direct access to the bank data using commands such
as poke, doke and loke then use these commands to find a bank's address
in memory and its size.
=START (get the start address of a bank)
s=START(b)
This function returns the start address of bank unmber b. Once it's
been removed, the location of the bank will never subsequently change.
So the result of this function will remain fixed for the lifetime of
the bank. Example:
Reserve As Work 3,2000
Print Start(3)
=LENGTH (Get the length of a bank)
l=length(b)
The LENGTH function returns the length in bytes of bank number b. If
the bank contains sprites then the number of sprites or icons will be
returned instead. A value of zero indicates that bank b does not exist.
Exaple:
Reserve as work 6,1000
Print Length(6)
Erase 6
Print Length(6)
Loading and saving banks 51
------------------------
Some programs will require many banks of information, a good example is
an adventure. This would need to load various graphics and sounds for
the different locations within the games domain. An Amiga 500 would
have great difficulty holding all this data at once and so it's best to
simply load the data at the appropriate time of use.
LOAD (Load one or more banks)
LOAD "filename"[,n]
The effect of this command varies depending on the type of file you are
loading. If the file holds several banks, then ALL current memory banks
will be erased before the new banks are loaded from the disc. However
if you're loading just a single bank, only this bank will replaced. The
optional destination point specifies the bank which is to be loaded
with your data. If it's omitted, then the data will be loaded into the
bank from which it was originally saved.
Sprite banks are treated slightly differently. In this case the
parameter n toggles between two separate loading modes. If n is omitted
or is assigned a value of zero, the current bank will completely
overwritten by the new sprites. Any other value for n forces the new
sprites to be *appended* to this bank. This allows you to combine
several sprite files into the same program. Example:
LOAD "AMOS_DATA:Sprites/Octopus.abk"
SAVE (Save one or more banks onto the disc)
SAVE "filenami"[,n]
The SAVE command saves your memory banks onto the disc. There are two
possible formats:
SAVE "filename.ABK"
This saves *ALL* currently defined banks into a single file onto your
disc.
SAVE "filename.ABK",n
The expanded form just saves memory bank number n. One should also be
sure to use the extension ABK at the end of the filename as this will
ensure you can identify that the file contains one or more memory
banks.
BSAVE (Save an unformatted block
in binary format)
BSAVE file$, start TO end
The memory stored between "start" and "end" is saved on the disc in
file$. This data is saved with no special formatting. Example:
BSAVE "Test",Start(7) TO Start(7)+Length(7)
The above example saves the data in memory bank 7 to disc. The
difference between this file and a saved file as a normal bank is that
SAVE writes out a special blank header that contains information
concerning the bank. This header is not present with a BSAVED file so
it cannot be loaded using LOAD.
WARNING: The sprites an icon banks are not stored as one chunk of
memory. Each object can reside anywhere in memory. Because AMOS uses
this flexible system of data storage you simply can't save the memory
bank using BSAVE.
BLOAD (load binary information into 52
a specified address or bank)
BLOAD file$, addr
The BLOAD command loads a file of binary data into memory. It does not
alter the incoming information in any way. There are two forms of this
function.
BLOAD file$, addr
File$ will be loaded from the disc into the address addr.
BLOAD file$, bank
File$ will be loaded into bank. This bank must have been previously
reserved, otherwise an error will be generated. Also be sure not to
load a file that is larger than the reserved bank, otherwise it will
over run the bank and start corrputing other areas of memory!
Memory fragmentation
--------------------
Sometimes, after a busy editing session, you may get an "Out of Memory"
error, even though the information line implie
Finding space for your variables
--------------------------------
As a default, all variables are stored in a memory area of exactly 8k
in length. Although this may seem incredibly meagre, it's easily
capable of holding around 2 pages of normal text, or 2000 numbers.
We've intentionally set it as small as possible so as to maximize the
amount of space available for your screens and memory banks.
SET BUFFER (set the size of the variable area)
SET BUFFER n
Sets the size of the variable area in your current program to "n"
kilobytes. This must be the FIRST instruction in your program
(excluding Rems). Otherwise you'll get an appropriate error message.
For an example of this feature see EXAMPLE 4.1 in the MANUAL folder.
SET BUFFER should be used in your program whenever you get an "out of
string space error". Increase the value in 5k increments until the
error disappears. If you run out of memory during this process, you'll
propably need to reduce the requirements of your program in some way.
See the CLOSE WORKBENCH and CLOSE EDITOR commands for more details.
=FREE (return the amount of free mem. in the variable area)
f=FREE
FREE returns the number of bytes which are currently available to hold
your variables. This value can be increased as required using the
previous SET BUFFER command.
Whenever FREE is called, the variable area is reorganized to provide
the maximum space for your variables. This process is known as "garbage
collection", and is normally performed automatically.
Due to the power of AMOS Basic, the entire procedure is usually
accomplished practically instantaneously. But if your variable area is
bery large and you're using a lot of strings, the garbage collection
routine might take several seconds to complete. Conceivably, this could
lead to a unexpected delay in the execution of your programs. Since the
garbage collection is totally essential, you may need to add an
explicit call to the FREE command when it will cause the least amount
of harm in your program.